package http

import (
	"context"
	"fmt"
	"net"
	"net/http"
	"smart-flow/container/config"
	"smart-flow/container/logger"
	"time"

	"go.uber.org/zap"

	"github.com/gin-gonic/gin"
)

type ServerManager struct {
	streamServer *http.Server
}

func (m *ServerManager) Start() bool {
	return m.startStreamServer()
}

func (m *ServerManager) startStreamServer() bool {
	gin.SetMode(gin.ReleaseMode)
	r := gin.New()
	r.Use(gin.Logger(), gin.Recovery())
	r.POST(config.PathStream, StreamHandle)
	listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", config.IpAddr, config.HttpStreamPort))
	if err != nil {
		logger.Logger.Error("[容器] http 服务监听错误", zap.String("ip", config.IpAddr), zap.Int("port", config.HttpStreamPort), zap.Error(err))
		return false
	}
	m.streamServer = &http.Server{Handler: r}
	errChan := make(chan error, 1)
	go func() {
		errChan <- m.streamServer.Serve(listener)
	}()
	select {
	case <-errChan:
		return false
	case <-time.After(time.Second):
		config.AddHttpPort(config.HttpStreamPort)
		logger.Logger.Info("[容器] http 服务启动成功", zap.String("ip", config.IpAddr), zap.Int("port", config.HttpStreamPort))
		return true
	}
}

func (m *ServerManager) Stop() {
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	_ = m.streamServer.Shutdown(ctx)
}

func StreamHandle(c *gin.Context) {
	var totalBytes int64
	buf := make([]byte, 8192) // 8KB 缓冲区
	for {
		n, err := c.Request.Body.Read(buf)
		if n > 0 {
			totalBytes += int64(n)
		}
		if err != nil {
			break // 即使遇到 EOF 或连接中断，也视为完成
		}
	}
	if totalBytes > 1024*1024 {
		logger.Logger.Info("[容器] http 接收数据统计(KB)", zap.Int64("byteSize", totalBytes/config.KB), zap.String("ip", c.RemoteIP()))
	}
	c.String(http.StatusOK, "ok")
}
